<template>
  <div id="group_details">
    <div class="group_content">
      <div class="header">
        <div class="left" @click="goStandbyPage">
          <i class="el-icon-arrow-left"></i>
        </div>
        <div class="group_name">{{ groupName }}</div>
        <div class="right"></div>
      </div>
      <div class="chat_content" ref="ChatContent" :style="opacity">
        <div v-if="recordShow" class="get_record" @click="getRecord">
          {{ getRecordTitle }}
        </div>
        <div
          :class="item.userId == myMsg.qaqUser.id ? 'my_item' : 'item'"
          ref="item"
          v-for="(item, index) in chatRecord"
          :key="index"
        >
          <div class="user_img">
            <img :src="$host + item.qaqUser.avatar" alt="" />
          </div>
          <div class="message">
            <div class="sendTime" v-if="sendTimeShow(index)">
              {{ randerTime(item.sendTime) }}
            </div>
            <div class="user_name">{{ item.userInfo.nickName }}</div>
            <div class="news" v-html="item.userMsg"></div>
          </div>
        </div>
      </div>
      <div class="input_box">
        <div class="goBottom" v-if="goBottomShow" @click="scrollToBottom">
          <div class="content">{{ unreadMsg }}</div>
        </div>
        <div class="resizeNone">
          <el-input
            type="textarea"
            autosize
            placeholder="请输入内容"
            v-model="textarea"
            autofocus="true"
            @keydown.enter.native="enterDown($event)"
          >
          </el-input>
          <!-- 表情包按钮 -->
          <div class="emoticon" @click.stop="emojiShow = !emojiShow">
            <svg class="icon" aria-hidden="true">
              <use xlink:href="#icon-slidebar_biaoqing"></use>
            </svg>
            <Emoticon v-if="emojiShow" :sendWebSocketMsg="sendWebSocketMsg" />
          </div>
        </div>
        <!-- 发送按钮 -->
        <div
          :class="textarea ? 'send_button' : 'send_button_n'"
          @click="sendWebSocketMsg(textarea)"
        >
          发送
        </div>
      </div>
    </div>
    <div class="group_details">
      <Information :groupId="this.groupId" />
    </div>
  </div>
</template>

<script>
  import Emoticon from '@/components/home/Emoticon'
  import Information from '@/components/home/Information'

  import { getGroupMember, getGroupMsgList } from '@/utils/chatBox'

  export default {
    name: 'GroupDetails',
    components: { Emoticon, Information },
    data() {
      return {
        textarea: '',  //用户输入的聊天内容
        groupMsg: [],  //群信息
        groupName: '加载中', //群聊名称
        getRecordTitle: '获取历史记录',
        goBottomShow: false, //是否显示返回聊天内容底部按钮
        unreadMsg: 0,  //未读消息
        chatRecord: [], //群聊历史消息,
        page: 1,        //页面请求的历史记录页数
        hasNextPage: true, //是否还有历史记录
        recordShow: false,  //是否显示获取历史记录按钮
        opacity: 'opacity: 0', //聊天盒子透明的，初始化是0，为了好看
        emojiShow: false,  //是否显示表情包按钮
      }
    },
    computed: {
      myMsg() {  //获取我的信息
        return JSON.parse(localStorage.getItem('user'))
      },
      groupId() {
        return this.$route.params.groupId
      }
    },
    watch: {
      groupName() {
        let that = this
        goBottom()
        function goBottom() {
          if (that.$refs.item === undefined) {
            setTimeout(() => {
              goBottom()
            })
          } else {
            that.scrollToBottom()
            that.opacity = ''
          }
        }
      },
      emojiShow(newVal) {
        if (newVal === true) {
          window.addEventListener('click', () => { this.emojiShow = false })
        }
      }
    },
    methods: {
      //获取群信息（群名称，群头像，群成员）
      async getGroupMember() {
        let { data: { data } } = await getGroupMember(this.groupId)
        this.groupMsg = data
        this.groupName = data.group.groupName
      },
      // 获取分页后的聊天内容
      async getGroupMsgList() {
        let { data: { data } } = await getGroupMsgList(this.groupId, this.page)
        this.chatRecord = data.list.reverse() //倒转
        this.hasNextPage = data.hasNextPage
      },
      //获取历史记录
      async getRecord() {
        if (this.hasNextPage) {
          this.getRecordTitle = '加载中...'
          this.page++
          let { data: { data: { list, hasNextPage } } } = await getGroupMsgList(this.groupId, this.page)
          this.chatRecord = list.reverse().concat(this.chatRecord)
          this.hasNextPage = hasNextPage
          this.getScrollHeight()
          this.getRecordTitle = '获取历史记录'
        } else this.getRecordTitle = '没有更多了'
      },
      //处理聊天信息上方的时间格式 以及是否显示
      randerTime(time) {
        //这是历史记录发送时间
        let old = new Date(time).getTime();
        const oldDate = new Date(old);
        const Y = oldDate.getFullYear() + '-';
        const M = (oldDate.getMonth() + 1 < 10 ? '0' + (oldDate.getMonth() + 1) : oldDate.getMonth() + 1) + '-';
        const D = (oldDate.getDate() < 10 ? '0' + oldDate.getDate() : oldDate.getDate()) + ' ';
        const h = (oldDate.getHours() < 10 ? '0' + oldDate.getHours() : oldDate.getHours()) + ':';
        const m = (oldDate.getMinutes() < 10 ? '0' + oldDate.getMinutes() : oldDate.getMinutes());
        const s = ':' + (oldDate.getSeconds() < 10 ? '0' + oldDate.getSeconds() : oldDate.getSeconds());
        //这是当前时间
        let now = new Date().getTime();
        const nowDate = new Date(now);
        //以下是对返回时间格式的判断
        if (nowDate.getFullYear() - oldDate.getFullYear() == 0) {
          if (nowDate.getMonth() - oldDate.getMonth() == 0) {
            if (nowDate.getDate() - oldDate.getDate() == 0) {
              return h + m + s         //如果是当天，只显示时分秒
            } else if (nowDate.getDate() - oldDate.getDate() == 1) {
              return '昨天 ' + h + m  //如果是昨天，显示昨天
            }
            return M + D + h + m   //如果不同日且不是昨天，显示月
          }
          return M + D + h + m   //如果不同月，显示月
        }
        return Y + M + D + h + m   //如果不同年，显示年
      },
      //是否显示本条消息的发送时间
      sendTimeShow(index) {
        //时间戳每隔600000就相当于间隔十分钟
        if (index == 0) return false  //如果这条消息是当前聊天框里的第一条，显示它的发送时间
        else {
          let oldMsg = this.chatRecord[index - 1]  //获取上一条消息的发送数据
          let newMsg = this.chatRecord[index]      //获取本条消息的发送时间
          let oldTime = new Date(oldMsg.sendTime).getTime()
          let newTime = new Date(newMsg.sendTime).getTime()
          if (newTime - oldTime > 600000) {        //如果本条消息的发送时间距离上一条超过了10分钟，则显示它
            return true
          }
        }
      },
      //让聊天内容滚动到最底部
      scrollToBottom() {
        this.$nextTick(() => {
          this.unreadMsg = 0 //让未读消息重置为 0
          //返回底部功能代码
          let ChatContent = this.$refs.ChatContent
          ChatContent.scrollTop = ChatContent.scrollHeight;
        })
      },
      //加载历史记录完毕后 重新滑动到加载之前的位置
      getScrollHeight() {
        let ChatContent = this.$refs.ChatContent
        let oldHeight = ChatContent.scrollHeight; //加载之前内容的搞定
        this.$nextTick(() => {
          let newChatContent = this.$refs.ChatContent
          //加载后的总的总高度减去之前的总高度等于加载前所在的位置
          newChatContent.scrollTop = newChatContent.scrollHeight - oldHeight;
        })
      },
      //点击回车取消textarea默认事件，并且发送消息
      enterDown(event) {
        if (event.key == 'Enter') {
          event.returnValue = false
          this.sendWebSocketMsg(this.textarea)
        }
      },
      //判断聊天框距离底部的位置，如果小于700，未读消息提示框隐藏
      handleScroll() {
        let ChatContent = this.$refs.ChatContent
        if (ChatContent.scrollHeight - ChatContent.scrollTop <= 700) {
          this.goBottomShow = false //让未读消息提示框隐藏
        }
        //当聊天框高度大于1500px时，显示获取历史记录按钮
        if (ChatContent.scrollHeight >= 1500) {
          this.recordShow = true
        }
      },
      //回到初始页面
      goStandbyPage() {
        this.$router.replace('/home/chatBox/standbyPage')
      },

      // webSocket
      //创建webSocket连接
      initWebSocket() {
        let userId = JSON.parse(localStorage.getItem('user')) ? JSON.parse(localStorage.getItem('user')).qaqUser.id : null
        let groupId_userId = this.groupId + "-" + userId
        this.ws = new WebSocket(`ws://zyl310.cn:8080/websocket/${groupId_userId}`)
        this.ws.onopen = this.handleWsOpen
        this.ws.onclose = this.handleWsClose
        this.ws.onerror = this.handleWsError
        this.ws.onmessage = this.handleWsMessage
      },
      //发送消息
      sendWebSocketMsg(msg) {
        if (msg !== '') {
          this.ws.send(JSON.stringify({
            groupId: parseInt(this.groupId),
            userId: this.myMsg.qaqUser.id,
            userMsg: msg,
            sendTime: new Date()
          }))
        }
        // 让每次发送消息都显示在最底端
        this.scrollToBottom()
        //清空输入框
        this.textarea = ''
      },
      handleWsOpen(e) {
        console.log('WenScoket Open', e);
      },
      handleWsClose(e) {
        console.log('断开连接', e);
      },
      handleWsError(e) {
        console.log('WenScoket Error', e);
        this.initWebSocket() //重新尝试连接
      },
      //接收消息的回调
      handleWsMessage(e) {
        let ChatContent = this.$refs.ChatContent
        //获取当前聊天页面距离聊天框底部的位置
        let distance = ChatContent.scrollHeight - ChatContent.scrollTop
        let receivedMsg = JSON.parse(e.data)
        this.chatRecord.push(receivedMsg)
        //当页面上滑500px时监听未读消息
        if (distance > 700) {
          this.unreadMsg++  //有消息发来，未读消息加一
          this.goBottomShow = true //显示未读消息提示框
          return
        }
        // 让每次消息更新都显示在最底端
        this.scrollToBottom()
      }
    },
    created() {
      this.getGroupMember()
      this.getGroupMsgList()
    },
    mounted() {
      this.initWebSocket()
      //绑定聊天框的滚动条事件
      this.$refs.ChatContent.addEventListener("scroll", this.handleScroll);
    },
    beforeDestroy() {
      //断开webSocket连接
      this.ws.close()
      //解绑聊天框的滚动条事件
      this.$refs.ChatContent.removeEventListener("scroll", this.handleScroll);
      window.removeEventListener('click', () => { this.emojiShow = false })
    },
  }
</script>

<style scoped>
  #group_details {
    flex: 1;
    display: flex;
    height: 100vh;
  }
  .group_content {
    flex: 1;
    display: flex;
    flex-direction: column;
    background-color: #36393f;
  }
  .group_content .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 48px;
    box-shadow: 0 1px 0 rgba(4, 4, 5, 0.2), 0 1.5px 0 rgba(6, 6, 7, 0.05),
      0 2px 0 rgba(4, 4, 5, 0.05);
  }
  .header .left,
  .header .right {
    width: 48px;
    height: 48px;
    text-align: center;
    font-size: 24px;
    line-height: 48px;
    color: #fff;
    cursor: pointer;
  }

  .header .group_name {
    flex: 1;
    text-align: center;
    font-weight: 800;
    color: #fff;
  }
  /* 聊天框内容 */
  .group_content .chat_content {
    flex: 1;
    margin: 0 15px;
    padding: 15px 0;
    overflow: auto;
    color: #d8d9da;
    /* 让文字可以被选中 */
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
  }
  /* 滚动条样式修改 */
  .chat_content::-webkit-scrollbar {
    width: 6px;
    /* height: 4px; */
  }
  .chat_content::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background: #000;
  }
  .chat_content .get_record {
    height: 15px;
    font-size: 8px;
    text-align: center;
    line-height: 15px;
  }
  .chat_content .item {
    position: relative;
    min-height: 50px;
    margin: 20px 10px;
  }
  .chat_content .my_item {
    position: relative;
    min-height: 50px;
    margin: 20px 10px;
  }
  .item .user_img {
    position: absolute;
    width: 48px;
    height: 48px;
    border-radius: 50%;
    overflow: hidden;
  }
  .my_item .user_img {
    position: absolute;
    right: 0;
    width: 48px;
    height: 48px;
    border-radius: 50%;
    overflow: hidden;
  }
  .user_img img {
    width: 100%;
    height: 100%;
  }
  .item .message {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    margin-left: 66px;
  }
  .item .message::after {
    position: absolute;
    top: 36px;
    left: -14px;
    content: "";
    display: block;
    width: 0px;
    height: 0px;
    border-width: 4px 8px 4px 8px;
    border-style: solid;
    border-color: transparent #40444b transparent transparent;
  }
  .my_item .message {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    margin-right: 66px;
  }
  .my_item .message::after {
    position: absolute;
    top: 36px;
    right: -14px;
    content: "";
    display: block;
    width: 0px;
    height: 0px;
    border-width: 4px 8px 4px 8px;
    border-style: solid;
    border-color: transparent transparent transparent #40444b;
  }
  .item .message .sendTime {
    position: absolute;
    right: 50%;
    transform: translateX(calc(50% - 33px));
    font-size: 12px;
  }
  .my_item .message .sendTime {
    position: absolute;
    left: 50%;
    transform: translateX(calc(-50% + 33px));
    font-size: 12px;
  }
  .message .user_name {
    font-size: small;
    height: 24px;
  }
  .message .news {
    padding: 10px;
    max-width: 60%;
    min-height: 24px;
    font-size: 14px;
    border-radius: 15px;
    background-color: #40444b;
    color: #c0c4cc;
    overflow: hidden;
  }
  .news /deep/ audio,
  .news /deep/ video,
  .news /deep/ iframe,
  .news /deep/ img {
    max-width: 100% !important;
  }

  /* 聊天输入框 */
  .group_content .input_box {
    display: flex;
    justify-content: space-around;
    margin-top: 10px;
    padding: 0 15px;
  }
  .input_box .resizeNone {
    position: relative;
    width: 93%;
  }
  .input_box .resizeNone /deep/ .el-textarea__inner {
    min-height: 44px !important;
    max-height: 135px !important;
    border: 0;
    margin-bottom: 20px;
    padding-right: 40px;
    background-color: #40444b;
    color: #c0c4cc;
    resize: none;
  }
  .input_box .resizeNone /deep/ .el-textarea__inner::-webkit-scrollbar {
    width: 4px;
    /* height: 4px; */
  }
  .input_box .resizeNone /deep/ .el-textarea__inner::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background: rgb(46, 45, 45);
  }
  /* 表情框 */
  .emoticon {
    position: absolute;
    top: 0;
    right: 4px;
    width: 28px;
    height: 28px;
    margin: 8px 5px 0 5px;
    border-radius: 50%;
    cursor: pointer;
  }
  .emoticon svg {
    width: 100%;
    height: 100%;
  }
  /* 发送消息按钮 */
  .input_box .send_button {
    width: 5%;
    height: 34px;
    margin-top: 5px;
    border-radius: 8px;
    font-size: 14px;
    text-align: center;
    line-height: 34px;
    background-color: #5865f2;
    color: #fff;
    cursor: pointer;
  }
  .input_box .send_button_n {
    width: 5%;
    height: 34px;
    margin-top: 5px;
    border-radius: 8px;
    font-size: 14px;
    text-align: center;
    line-height: 34px;
    background-color: #444c95;
    color: #97999b;
    cursor: not-allowed;
  }
  /* 返回聊天框底部按钮 */
  .input_box .goBottom {
    position: absolute;
    top: -40px;
    right: 70px;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    text-align: center;
    line-height: 24px;
    background-color: #5865f2;
  }
  .goBottom::after {
    position: absolute;
    top: 21px;
    left: 50%;
    transform: translateX(-50%);
    content: "";
    display: block;
    width: 0px;
    height: 0px;
    border-width: 8px;
    border-style: solid;
    border-color: #5865f2 transparent transparent transparent;
  }

  /* 右边群展示框 */
  .group_details {
    width: 312px;
    background-color: #2f3136;
  }
</style>